// a.js 同级目录下 运行cmd>> node a.js

const fs = require("fs");
const path = require('path');

// ui的目录, 手动要修改
let ENTRY = 'pages/Alert';

const KEYS = ["x", "y", "width", "height", "left", "right", "top", "bottom", "centerX", "centerY", "fontSize",
	"pivotX", "pivotY"];

fileDisplay(ENTRY);

function fileDisplay(filePath) {
	fs.readdir(filePath, function(err, files) {
		if (err) return console.error(err);
		
		files.forEach(filename=> {
			var filedir = path.join(filePath, filename);
			fs.stat(filedir, function(eror, stats) {
				if (eror) return console.error('获取文件stats失败');
				if (stats.isFile()) {
					dealFile(filedir);
				} else if (stats.isDirectory()) {
					fileDisplay(filedir);
				}
			});

		});

	});
}


function dealFile(filedir) {
	fs.readFile(filedir, (err, jsondata) => {
		if (err) return console.log(err);
		jsondata = JSON.parse(jsondata);
		
		changeData(jsondata);

		console.log(filedir);

		fs.writeFile(filedir, JSON.stringify(jsondata),(err, jsondata) => {
			if (err) console.log(err);
		});


		function changeData(node) {
			if (node.props) {
				Object.keys(node.props).forEach(key=> {
					if (KEYS.includes(key)) {
						node.props[key] = node.props[key]/2;
					} else if (key==="sizeGrid") {
						let arr = node.props[key].split(",");
						arr = arr.map((val, index)=> val/2);
						node.props[key] = arr.join(",");
					}
				});
			}

			if (node.child) {
				node.child.forEach(child=> {
					changeData(child)
				});
			}
		}

	});

}


function deepClone(values) {
    var copy;
    if (null == values || "object" != typeof values) return values;
    if (values instanceof Date) {
        copy = new Date();
        copy.setTime(values.getTime());
        return copy;
    }
    if (values instanceof Array) {
        copy = [];
        for (var i = 0, len = values.length; i < len; i++) {
            copy[i] = deepClone(values[i]);
        }
        return copy;
    }
    if (values instanceof Object) {
        copy = {};
        for (var attr in values) {
            if (values.hasOwnProperty(attr)) copy[attr] = deepClone(values[attr]);
        }
        return copy;
    }
    throw new Error("Unable to copy values! Its type isn't supported.");
}